import os,time
import sys
from django.utils import timezone
from multiprocessing import Pool
import django
from tkinter import messagebox
from conf.env import *
import requests,json
from loguru import logger
from datetime import datetime,date,timedelta
from apps.TabletInfo.models import TabletInfo
from apps.prescription.handler import writelog,writeExceptlog


from apps.prescription.models import Prescription, Drug
from apps.prescription.handler import atmtorad
from op_drf.dj_utils import flow_code_manage
from op_drf.dj_utils import create_by_serializer
from rest_framework.request import Request


def multi_processgethisinfo():

    # 接口
    autogethisinfo()


def autogethisinfo():
    # 增加查询条件和身份验证,未传入参数的设置
    try:
        # 获取token的接口
        # 拼接最终的token,注意中间有个空格
        token = "Bearer"+" "+"123"
        # bizCode="PlaintextUserLogin"
        # token_url = f"https://{IP}:{PORT}/api/thc-data/dt/api/{bizCode}"
        # logger.debug(token_url)
        # form_data = {
        #     "name":USERNAME,
        #     "organizationId":ORGANIZATIONID,
        #     "password":PASSWORD
        # }
        # try:
        #     res_token = requests.post(token_url,data=form_data).content.decode()
        #     res_token = requests.post(token_url,data=form_data)
        #     token = re.findall('"token":(.+?)',res_token)[0]     # 正则取出来的是列表，要进行列表取值
        # except Exception as e:
        #     logger.debug(e)

        # HIS 接口入参数
        # {
        #     "putDrugTypes": [],
        #     "areaId": "",
        #     "areaName": "全部",
        #     "startTime": "2024-05-27 00:00:00",
        #     "endTime": "2024-05-27 23:59:59",
        #     "storageRoomId": "d06663bf-f3b7-4b40-a4df-0253b31d08d0",
        # }
        # 时间范围
        now = timezone.now()
        one_days_ago = now - timedelta(days=1)
        one_days_later = now - timedelta(days=-1)
        startTime = one_days_ago.strftime('%Y-%m-%d %H:%M:%S')
        endTime = one_days_later.strftime('%Y-%m-%d %H:%M:%S')
        # 还说可以添加其他参数，例如传入口服药的参数
        # 确定HIS接口怎么传参，根据HIS接口形成传参，参数是什么？
        bizCode="WhGetDispensingTaskCollect"
        # 自定义摆药分类  1注射类 2口服类 3输液类 4外用类5中药口服类
        # 病区,必填
        areaId = ""
        # 库房Id,必填
        storageRoomId = ""
        # 摆药分类
        putDrugTypes="2"
        params = f"areaId={areaId}&storageRoomId={storageRoomId}&putDrugTypes={putDrugTypes}&startTime={startTime}&endTime={endTime}"
        # url = f"https://{IP}:{PORT}/api/thc-data/dt/api/{bizCode}?{params}"
        # url = f"http://{IP}:{PORT}/hisprescription.asmx/get_hisprescripton?{params}"
		url = HIS_URL + f"?{params}"
        logger.debug(url)
        headers_={
            "authorization":token
        }
        res_ = requests.get(url,headers=headers_)

        if res_.status_code == 200:
            json_data = res_.content.decode().replace('<string xmlns="http://tempuri.org/">', '')
            json_data = json_data.replace('</string>','')
            json_data = json_data.replace('<?xml version="1.0" encoding="utf-8"?>', '')
            py_data = json.loads(json_data)
            # 根据实际接口返回格式，获取相应的数据
            head = py_data.get("head", None)
            data = py_data.get("data", None)
            logger.debug(data)
            assert all ([head , data]), f"获取接口数据失败"
            errCode = head.get("errCode")
            if errCode == 0:
                itemlist = data.get("itemList", None)
                for item in itemlist:
                    if item:
                        # logger.debug(item)
                        # 处方时间  dispensingTime
                        dispensingTime = item.get("dispensingTime", None)

                        # 首先判断有没有形成处方，有的话直接跳过
                        # 处方id
                        orderid = item.get("orderId", None)
                        # logger.debug(orderid)
                        if Prescription.objects.filter(is_delete=False,orderId=orderid):
                            continue
                        # 添加处方
                        serial_num = flow_code_manage(value="prescription_order")
                        # logger.debug(serial_num)
                        if not Prescription.objects.filter(OrderNum=serial_num):

                            # 处方
                            orderid = item.get("orderId", None)
                            prescrip_list = Prescription.objects.filter(is_delete=False,orderId=orderid)
                            if prescrip_list:
                                continue
                            # 这儿形成处方
                            serial_num = flow_code_manage(value="prescription_order")
                            if Prescription.objects.filter(OrderNum=serial_num):
                                pass
                            else:
                                # 诊疗科室
                                DptmtCd = item.get("executeProviderId", None)
                                # logger.debug(DptmtCd)
                                # 病患
                                PtntNm = item.get("patientName", None)
                                PtntNum = item.get("patientId", None)
                                DoctorNm = item.get("doctorName", None)
                                # 医嘱日期时间，拆分为服药日期和频次
                                implementTime = item.get("implementTime", None)
                                takedt = implementTime.split(" ")[0]
                                # logger.debug(implementTime)
                                if implementTime:
                                    use_freqtime = "".join(implementTime.split(" ")[1].split(':')[0:2])
                                    # logger.debug(use_freqtime)
                                # 病床号
                                BedNum = item.get("bedNum", None)
                                # 药品编号 、药品名称
                                MedCd = item.get("materialsCode", None)
                                MedNm = item.get("materialName", None)


                                # 服药天数
                                takedays = item.get("useDay", 1)
                                # 药品备注
                                MedNote = item.get("entrust", ' ')

                                # 诊疗科id
                                executeProviderId = item.get("executeProviderId", None)
                                # 病区id代替病区编号
                                WardCd = item.get("areaId", None)
                                MedUnit = item.get("unitName", None)
                                # 服药时间，哈特瑞姆不使用频次字段，需要从医嘱时间中拆分

                                useFreqTime = item.get("useFreqTime", None)
                                num = item.get("num", None)
                                age = item.get("age", None)
                                sex = item.get("sex", None)

                                # 用药途径 1:口服 2:直肠用药   ...
                                employ = item.get("employ", 0)
                                # 医嘱类型 0:临时医嘱 1:长期医嘱
                                termType = item.get("termType", "")
                                # 用药途径，可以传入是数字也可以是汉字
                                if MedUnit in ['片', '粒'] and employ in ["1","口服"]:
                                    prescrip_list = Prescription.objects.filter(is_delete=False,orderId=orderid)

                                    if not prescrip_list:
                                        prescrip_obj = Prescription.objects.create(OrderNum=serial_num,
                                                                                   is_delete=False,
                                                                                   orderId=orderid,
                                                                                   OrderDt=takedt,
                                                                                   OrderDtm=dispensingTime,
                                                                                   DptmtCd=DptmtCd,
                                                                                   PtntNm=PtntNm,
                                                                                   PtntNum=PtntNum,
                                                                                   DoctorNm=DoctorNm,
                                                                                   RoomNum=BedNum,
                                                                                   BedNum=BedNum,
                                                                                   WardCd=WardCd,
                                                                                   executeProviderId=executeProviderId,
                                                                                   OrderStatus="0",
                                                                                   age=age,
                                                                                   sex=sex,
                                                                                   inoutclsf=termType
                                                                                   );
                                    else:
                                        prescrip_obj = prescrip_list[0]
                                    if prescrip_obj:
                                        drug_list = Drug.objects.filter(is_delete=False,
                                                                        prescrption=prescrip_obj,
                                                                        MedNm=MedNm,
                                                                        MedCd=MedCd,
                                                                        MedUnit=MedUnit,
                                                                        takedt=takedt)
                                        if not drug_list:
                                            # 通过药品编号获取药品基础信息，并写入药品数据表
                                            tabletinfo_list = TabletInfo.objects.filter(tblt_cd=MedCd)
                                            medspec = ''
                                            if tabletinfo_list:
                                                tabletinfo_obj = tabletinfo_list[0]
                                                medspec = tabletinfo_obj.tblt_spec
                                                MedNm = tabletinfo_obj.tblt_nm

                                            try:
                                                Drug.objects.create(prescrption=prescrip_obj,
                                                                    MedNm=MedNm,
                                                                    MedCd=MedCd,
                                                                    is_delete=False,
                                                                    MedUnit=MedUnit,
                                                                    takedt=takedt,
                                                                    takedays=takedays,
                                                                    doselist_time=use_freqtime,
                                                                    doselist_dose=num,
                                                                    MedNote=MedNote,
                                                                    MedSpec=medspec,
                                                                    tablet=tabletinfo_obj
                                                                    )
                                            except Exception as e:
                                                logger.debug(e)
                                        atmtorad(prescrip_obj.pk)
                writelog("成功")
            else:
                writeExceptlog(2, '获取数据失败')
    except Exception as e:
        writeExceptlog(1, 'HIS接口连接失败')